<?php

namespace App\Console\Commands;

use Illuminate\Console\Command;

class RepositoryCommand extends Command
{
    /**
     * 创建repository 绑定控制器和模型
     *
     * @var string
     */
    protected $signature = 'make:repository {--repository=} {--model=}';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'Make An Model Repository for Api';

    /**
     * Create a new command instance.
     *
     * @return void
     */
    public function __construct()
    {
        parent::__construct();
    }

    /**
     * Execute the console command.
     *
     * @return mixed
     */
    public function handle()
    {
        $path = app_path('Repositories');

        $repository_name = $this->option('repository');
        $model =  $this->option('model');


        if(!($repository_name && $model)) {
            $repository_name = $this->ask('repository name ?');
            $model = $this->ask('this repository binding model name ?');
        }

        $a = explode("/",$repository_name);

        $spaceName = 'App\Repositories';
        $repository = end($a);

        if(count($a) > 1 ) {
            unset($a[count($a)-1]);
            $spaceName .= '\\'. implode("\\",$a);

            foreach ($a as $v){
                $path .= '/'.$v;
                try{
                    @mkdir($path);
                }catch (\Exception $e){
                    $this->line($e->getMessage());die();
                }
            }
        }

        $template = $this->template($spaceName,$repository,$model);

        $file = $path.'/'.$repository.'.php';

        if(file_exists($file)){
            $this->line($repository.' is exists !');die();
        }

        try{
            $f = fopen($file,'w');
            fwrite($f,$template);
            fclose($f);
            $this->line($spaceName.'\\'.$repository.' is created !');

        }catch (\Exception $e){
            $this->line($e->getMessage());die();
        }

    }

    public function template($spaceName,$repository,$model)
    {
        $str = file_get_contents(storage_path('app\template\repositoryTemplate.php'));
        $str = str_replace(['spaceName','repositoryName','{model}'],[$spaceName,$repository,$model],$str);

        return $str;
    }
}
